package com.rivues.module.datamodel.web.handler;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.View;
import javax.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.io.ByteStreams;
import com.itextpdf.text.pdf.codec.Base64.InputStream;
import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.auth.AuthInterface;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.Auth;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.CubeLevel;
import com.rivues.module.platform.web.model.CubeMeasure;
import com.rivues.module.platform.web.model.CubeMetadata;
import com.rivues.module.platform.web.model.DataDic;
import com.rivues.module.platform.web.model.Database;
import com.rivues.module.platform.web.model.Dimension;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.PublishedCube;
import com.rivues.module.platform.web.model.Role;
import com.rivues.module.platform.web.model.TableProperties;
import com.rivues.module.platform.web.model.TableTask;
import com.rivues.module.platform.web.model.TypeCategory;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.platform.web.model.UserOrgan;
import com.rivues.util.RivuTools;
import com.rivues.util.data.DatabaseMetaDataHandler;
import com.rivues.util.datasource.DataSource;
import com.rivues.util.iface.authz.UserAuthzFactory;
import com.rivues.util.local.LocalTools;
import com.rivues.util.serialize.JSON;
import com.rivues.util.service.ServiceHelper;
import com.rivues.util.service.business.DataSourceService;
  
@Controller  
@RequestMapping("/{orgi}/dm/cube")  
public class CubeController extends Handler{  
	private final Logger log = LoggerFactory.getLogger(LogIntercreptorHandler.class); 
	
	@Autowired
    private AuthInterface authInterface;
	/**
	 * 模型首页加载
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value="/index" , name="index" , type="dm",subtype="cube")
    public ModelAndView index(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
    	ModelAndView view = request(super.createDMTempletResponse("/pages/datamodel/cube/index") , orgi) ;
    	view.addObject("cubePackageList", super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("ctype", RivuDataContext.TypeCategory.CUBE.toString())).addOrder(Order.asc("name")))) ;
    	view.addObject("cubeList", super.getService().findAllByCriteria(DetachedCriteria.forClass(Cube.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("typeid", "0")).addOrder(Order.asc("name")))) ;
    	view.addObject("dicid", "0") ;
    	return view ;
    }
    /**
     * 模型列表加载
     * @param request
     * @param orgi
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubedic/{dicid}" , name="index" , type="dm",subtype="cube")
    public ModelAndView index(HttpServletRequest request , @PathVariable String orgi , @PathVariable String dicid) throws Exception{  
    	ModelAndView view = request(super.createDMTempletResponse("/pages/datamodel/cube/index") , orgi) ;
    	view.addObject("cubePackageList", super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("ctype", RivuDataContext.TypeCategory.CUBE.toString())).addOrder(Order.asc("name")))) ;
    	view.addObject("cubeList", super.getService().findAllByCriteria(DetachedCriteria.forClass(Cube.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("typeid", dicid)).addOrder(Order.asc("name")))) ;
    	view.addObject("locationdics",this.getAllParents(dicid, new ArrayList<TypeCategory>(), orgi));
    	view.addObject("dicid", dicid) ;
    	return view ;
    }
    
    @RequestMapping(value="/publishcube" , name="publishcube" , type="dm",subtype="cube")
    public ModelAndView publishcube(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/publishcube") , orgi) ;
    	view.addObject("cubePackageList", super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("ctype", RivuDataContext.TypeCategory.CUBE.toString())))) ;
    	view.addObject("cubeList", super.getService().findAllByCriteria(DetachedCriteria.forClass(PublishedCube.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("typeid", "0")))) ;
    	view.addObject("dicid","0");
    	return view ;
    }
    
    @RequestMapping(value="/publishcubelist/{dicid}" , name="publishcubelist" , type="dm",subtype="cube")
    public ModelAndView publishcubelist(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/publishcubelist") , orgi) ;
    	view.addObject("cubeList", super.getService().findAllByCriteria(DetachedCriteria.forClass(PublishedCube.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("typeid", dicid)))) ;
    	view.addObject("dicid",dicid);
    	return view ;
    }
    @RequestMapping(value="/publishcubedel/{dicid}/{id}" , name="publishcubedel" , type="dm",subtype="cube")
    public ModelAndView publishcubedel(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid, @PathVariable String id) throws Exception{
    	List<JobDetail> jobs = super.getService().findAllByCriteria(DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("taskid", id))) ;
    	String msg = null;
    	if(jobs.size()>0){
    		msg = "faild_exist_job";
    	}else{
    		PublishedCube cube = new PublishedCube();
        	cube.setId(id);
        	super.getService().deleteIObject(cube);
    	}
    	
    	ModelAndView view = publishcubelist(request, orgi, dicid);
    	view.addObject("msg",msg);
    	return view ;
    }
    /**
     * 模型目录添加页面加载
     * @param request
     * @param orgi
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{dicid}/cubedicadd" , name="cubedicadd" , type="dm",subtype="cube")
    public ModelAndView cubedicadd(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubedicadd") , orgi) ;
    	
    	TypeCategory category = null;
    	if("0".equals(dicid)){
    		category = new TypeCategory();
    		category.setId("0");
    		category.setName("数据模型目录（/）");
    	}else{
    		category = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, dicid);
    	}
    	view.addObject("category", category) ;
    	view.addObject("dicid", dicid) ;
    	return view ;
    }
    /**
     * 模型目录添加
     * @param request
     * @param orgi
     * @param dicid
     * @param cubedic
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{dicid}/cubedicaddo" , name="cubedicaddo" , type="dm",subtype="cube")
    public ModelAndView cubedicaddo(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid ,@Valid TypeCategory cubedic) throws Exception{  
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("name", cubedic.getName())).add(Restrictions.eq("parentid", dicid)).add(Restrictions.eq("orgi", orgi))) ;
    	ResponseData response = new ResponseData("redirect:/{orgi}/dm/cube/index.html") ;
    	if(count==0){
    		cubedic.setOrgi(orgi) ;
    		cubedic.setCtype(RivuDataContext.TypeCategory.CUBE.toString()) ;
    		cubedic.setCreater(super.getUser(request).getId());
    		cubedic.setCreatetime(new Date());
    		super.getService().saveIObject(cubedic) ;
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cubedic.getId()).append(".html?msgcode=I_MANAGE_80010001").toString()) ;
    	}else{
    		response.setPage("redirect:/{orgi}/dm/cube/cubedic/{dicid}.html?msgcode=E_MANAGE_80010002") ;
        }
    	return super.request( response , orgi) ;
    }
    /**
     * 模型目录编辑页面加载
     * @param request
     * @param orgi
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{dicid}/cubedicedit" , name="cubedicedit" , type="dm",subtype="cube")
    public ModelAndView cubedicedit(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubedicedit") , orgi) ;
    	TypeCategory cubedic = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, dicid);
    	TypeCategory category = null;
    	if("0".equals(dicid)){
    		category = new TypeCategory();
    		category.setId("0");
    		category.setName("数据模型目录（/）");
    	}else{
    		category = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, dicid);
    	}
    	
    	//显示父级目录
    	if(!"0".equals(category.getParentid())){
    		TypeCategory precategory = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, category.getParentid());
    		view.addObject("precategory", precategory) ;
    	}
    	view.addObject("cubedic", cubedic) ;
    	view.addObject("dicid", dicid) ;
    	view.addObject("category", category) ;
    	return view ;
    }
    /**
     * 模型目录编辑
     * @param request
     * @param orgi
     * @param dicid
     * @param cubedic
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{dicid}/cubediceditdo" , name="cubediceditdo" , type="dm",subtype="cube")
    public ModelAndView cubediceditdo(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid ,@Valid TypeCategory cubedic) throws Exception{  
    	TypeCategory category = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, cubedic.getId());
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("name", cubedic.getName())).add(Restrictions.eq("parentid", category.getParentid())).add(Restrictions.eq("orgi", orgi))) ;
    	ResponseData response = new ResponseData("redirect:/{orgi}/dm/cube/index.html") ;
    	
    	if(!cubedic.getName().equals(category.getName())&&count>0){
    		response.setPage("redirect:/{orgi}/dm/cube/cubedic/{dicid}.html?msgcode=E_MANAGE_80010002") ;
    		
    	}else{
    		
    		cubedic.setOrgi(orgi) ;
    		cubedic.setCtype(RivuDataContext.TypeCategory.CUBE.toString()) ;
    		cubedic.setCreater(category.getCreater());
    		cubedic.setCreatetime(category.getCreatetime());
    		cubedic.setUpdatetime(new Date());
    		cubedic.setCatetype(RivuDataContext.TypeCategory.CUBE.toString()) ;
    		super.getService().updateIObject(cubedic) ;
    		response.setPage("redirect:/{orgi}/dm/cube/cubedic/{dicid}.html?msgcode=I_MANAGE_80010003") ;
        }
    	return super.request( response , orgi) ;
    }
    /**
     * 模型目录删除
     * @param request
     * @param orgi
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubedicrm/{dicid}" , name="cubedicrm" , type="dm",subtype="cube")
    public ModelAndView cubedicrm(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid ) throws Exception{  
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("parentid", dicid)).add(Restrictions.eq("orgi", orgi))) ;
    	ResponseData response = new ResponseData("redirect:/{orgi}/dm/cube/index.html") ;
    	if(count==0){
    		count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Cube.class).add(Restrictions.eq("typeid", dicid)).add(Restrictions.eq("orgi", orgi))) ;
        	if(count==0){
        		
	    		TypeCategory cubedic = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, dicid);
	    		super.getService().deleteIObject(cubedic) ;
	    		response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cubedic.getParentid()).append(".html?msgcode=I_MANAGE_80010004").toString()) ;
        	}else{
        		response = new ResponseData("redirect:/{orgi}/dm/cube/cubedic/{dicid}.html?msgcode=E_MANAGE_80010004") ;
        	}
        }else{
    		response = new ResponseData("redirect:/{orgi}/dm/cube/cubedic/{dicid}.html?msgcode=E_MANAGE_80010003") ;
        }
    	return super.request( response , orgi) ;
    }
    /**
     * 模型添加页面加载
     * @param request
     * @param orgi
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{dicid}/cubeadd" , name="cubeadd" , type="dm",subtype="cube")
    public ModelAndView cubeadd(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid ) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubeadd") , orgi) ;
    	List<Database> databaseList = super.getService().findAllByCriteria(DetachedCriteria.forClass(Database.class).add(Restrictions.eq("orgi", orgi))) ;
    	TypeCategory category = null;
    	if("0".equals(dicid)){
    		category = new TypeCategory();
    		category.setId("0");
    		category.setName("数据模型目录（/）");
    	}else{
    		category = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, dicid);
    	}
    	view.addObject("category", category) ;
    	view.addObject("databaseList", databaseList) ;
    	view.addObject("dicid", dicid) ;
    	return view ;
    }
    
    @RequestMapping(value="/{dicid}/cubeimport" , name="cubeimport" , type="dm",subtype="cube")
    public ModelAndView cubeimport(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid ) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubeimport") , orgi) ;
    	List<Database> databaseList = super.getService().findAllByCriteria(DetachedCriteria.forClass(Database.class).add(Restrictions.eq("orgi", orgi))) ;
    	TypeCategory category = null;
    	if("0".equals(dicid)){
    		category = new TypeCategory();
    		category.setId("0");
    		category.setName("数据模型目录（/）");
    	}else{
    		category = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, dicid);
    	}
    	view.addObject("category", category) ;
    	view.addObject("databaseList", databaseList) ;
    	view.addObject("dicid", dicid) ;
    	return view ;
    }
    
    @RequestMapping(value="/cubeimporto" , name="cubeimporto" , type="dm",subtype="cube")
    public ModelAndView cubeimporto(HttpServletRequest request , @PathVariable String orgi,@Valid Cube cube,@RequestParam MultipartFile file) throws Exception{  
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Cube.class).add(Restrictions.eq("name", cube.getName())).add(Restrictions.eq("typeid", cube.getTypeid())).add(Restrictions.eq("orgi", orgi))) ;
    	ResponseData response = new ResponseData("redirect:/{orgi}/dm/cube/index.html") ;
    	
    	
    	Cube c = (Cube)JSON.parseObject(RivuTools.decryption(new String(file.getBytes())), Cube.class);
    	if(count==0){
    		c.setOrgi(orgi) ;
    		c.setCreater(super.getUser(request).getId());
    		c.setCreatetime(new Date());
    		c.setName(cube.getName());
    		c.setTypeid(cube.getTypeid());
    		c.setDb(cube.getDb());
    		List<CubeMetadata> metadata = c.getMetadata();
			List<Dimension> dimension = c.getDimension();
			List<CubeMeasure> measure = c.getMeasure();
			List<Cube> cubeList = super.getService().findAllByCriteria(DetachedCriteria.forClass(Cube.class)
					.add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("id", c.getId()))) ;
			if(cubeList.size()==0){
				super.getService().saveIObject(c);
			}
			Database db = (Database) super.getService().getIObjectByPK(Database.class, cube.getDb()) ;
			for (int j = 0; j < metadata.size(); j++) {
				metadata.get(j).setId(null);
				metadata.get(j).setCube(c.getId());
				/**
				 * 
				 */
				List<TableTask> tableTaskList = super.getService().findAllByCriteria(DetachedCriteria.forClass(TableTask.class)
					.add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("id", metadata.get(j).getTb().getId()))) ;
				if(tableTaskList.size()==0){
					metadata.get(j).getTb().setDatabase(db);
					metadata.get(j).getTb().setDbid(cube.getDb()) ;
					metadata.get(j).getTb().setTabledirid("0");
					super.getService().saveIObject(metadata.get(j).getTb());
					for(TableProperties tp: metadata.get(j).getTb().getTableproperty()){
						List<TableProperties> tpList = super.getService().findAllByCriteria(DetachedCriteria.forClass(TableProperties.class)
								.add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("id", tp.getId()))) ;
						if(tpList.size()==0){
							super.getService().saveIObject(tp);
						}
					}
				}
				super.getService().updateIObject(metadata.get(j));
			}

			for (int j = 0; j < dimension.size(); j++) {
				List<CubeLevel> levels = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeLevel.class)
					.add(Restrictions.eq("orgi", orgi))
					.add(Restrictions.eq("dimid", dimension.get(j).getId())));
				dimension.get(j).setCubeid(c.getId());
				for(CubeLevel level : dimension.get(j).getCubeLevel()){
					List<CubeLevel> levelList = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeLevel.class)
							.add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("id", level.getId()))) ;
					if(levelList.size() ==0 ){
						super.getService().saveIObject(level) ;
					}
				}
				List<Dimension> dimList = super.getService().findAllByCriteria(DetachedCriteria.forClass(Dimension.class)
						.add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("id", dimension.get(j).getId()))) ;
				if(dimList.size()==0){
					super.getService().saveIObject(dimension.get(j));
				}
				for (int k = 0; k < levels.size(); k++) {
					levels.get(k).setDimid(dimension.get(j).getId());
					levels.get(k).setCubeid(c.getId());
					super.getService().updateIObject(levels.get(k));
				}
			}

			for (int j = 0; j < measure.size(); j++) {
				measure.get(j).setCubeid(c.getId());
				List<CubeMeasure> meaList = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class)
						.add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("id", measure.get(j).getId()))) ;
				if(meaList.size()==0){
					super.getService().updateIObject(measure.get(j));
				}
			}
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cube.getTypeid()).append(".html?msgcode=S_DM_80010005").toString()) ;
    	}else{
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cube.getTypeid()).append(".html?msgcode=E_DM_80010006").toString()) ;
        }
    	return super.request( response , orgi) ;
    }
    
    /**
     * 模型添加
     * @param request
     * @param orgi
     * @param cube
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubeddo" , name="cubeddo" , type="dm",subtype="cube")
    public ModelAndView cubeddo(HttpServletRequest request , @PathVariable String orgi,@Valid Cube cube) throws Exception{  
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Cube.class).add(Restrictions.eq("name", cube.getName())).add(Restrictions.eq("typeid", cube.getTypeid())).add(Restrictions.eq("orgi", orgi))) ;
    	ResponseData response = new ResponseData("redirect:/{orgi}/dm/cube/index.html") ;
    	if(count==0){
    		cube.setOrgi(orgi) ;
    		cube.setCreater(super.getUser(request).getId());
    		cube.setCreatetime(new Date());
    		cube.setCode(RivuTools.getCode());
    		super.getService().saveIObject(cube) ;
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cube.getTypeid()).append(".html?msgcode=S_DM_80010005").toString()) ;
    	}else{
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cube.getTypeid()).append(".html?msgcode=E_DM_80010006").toString()) ;
        }
    	return super.request( response , orgi) ;
    }
    
    /**
     * 模型编辑页面加载
     */
    @RequestMapping(value="/{dicid}/cubeedit/{cobeid}" , name="cubeedit" , type="dm",subtype="cube")
    public ModelAndView cubeedit(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dicid,@PathVariable String cobeid ) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubeedit") , orgi) ;
    	Cube cube = (Cube)super.getService().getIObjectByPK(Cube.class, cobeid);
    	List<Database> databaseList = super.getService().findAllByCriteria(DetachedCriteria.forClass(Database.class).add(Restrictions.eq("orgi", orgi))) ;
    	TypeCategory category = null;
    	if("0".equals(cube.getTypeid())){
    		category = new TypeCategory();
    		category.setId("0");
    		category.setName("数据模型目录（/）");
    	}else{
    		category = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, dicid);
    	}
    	view.addObject("category", category) ;
    	view.addObject("databaseList", databaseList) ;
    	view.addObject("dicid", dicid) ;
    	view.addObject("cube", cube) ;
    	return view ;
    }
    
    /**
     * 模型编辑
     * @param request
     * @param orgi
     * @param cube
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubeedito" , name="cubeedito" , type="dm",subtype="cube")
    public ModelAndView cubeedito(HttpServletRequest request , @PathVariable String orgi,@Valid Cube cube) throws Exception{  
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Cube.class).add(Restrictions.eq("name", cube.getName())).add(Restrictions.eq("typeid", cube.getTypeid())).add(Restrictions.eq("orgi", orgi))) ;
    	Cube c = (Cube)super.getService().getIObjectByPK(Cube.class, cube.getId());
    	ResponseData response = new ResponseData("redirect:/{orgi}/dm/cube/index.html") ;
    	if(!c.getName().equals(cube.getName())&&count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cube.getTypeid()).append(".html?msgcode=E_DM_80010008").toString()) ;
    	}else{
    		cube.setOrgi(c.getOrgi()) ;
    		cube.setCreater(c.getCreater());
    		cube.setCreatetime(c.getCreatetime());
    		cube.setUpdatetime(new Date());
    		cube.setCode(RivuTools.getCode());
    		super.getService().updateIObject(cube);
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(cube.getTypeid()).append(".html?msgcode=S_DM_80010007").toString()) ;
        }
    	return super.request( response , orgi) ;
    }
    /**
     * 模型删除
     * @param request
     * @param orgi
     * @param cubeid
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{dicid}/cubedelo/{cubeid}" , name="cubedelo" , type="dm",subtype="cube")
    public ModelAndView cubedelo(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid, @PathVariable String dicid) throws Exception{  
    	ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=S_DM_80010009").toString()) ;
    	
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeLevel.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    	if(count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=E_DM_80010009").toString());
    		return super.request( response , orgi);
    	}
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    	if(count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=E_DM_80010009").toString());
    		return super.request( response , orgi);
    	}
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeMetadata.class).add(Restrictions.eq("cube", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    	if(count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=E_DM_80010009").toString());
    		return super.request( response , orgi);
    	}
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Dimension.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    	if(count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=E_DM_80010009").toString());
    		return super.request( response , orgi);
    	}
    	super.getService().deleteIObject(super.getService().getIObjectByPK(Cube.class, cubeid));
    	return super.request( response , orgi) ;
    }
    
    /**
     * 模型复制页面加载
     * @param request
     * @param orgi
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubecopy" , name="cubecopy" , type="dm",subtype="cube")
    public ModelAndView cubecopy(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubecopy") , orgi) ;
    	view.addObject("cubePackageList", super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("ctype", RivuDataContext.TypeCategory.CUBE.toString())))) ;
    	return view ;
    }
    
    /**
     * 模型复制
     * @param request
     * @param orgi
     * @param cubeids
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubecopyList" , name="cubecopyList" , type="dm",subtype="cube")
    public ModelAndView cubecopyList(HttpServletRequest request , @PathVariable String orgi,@Valid String[] cubeids,@Valid String dicid) throws Exception{  
    	ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=S_DM_80010020").toString()) ;
    	Cube cube = null;
    	for (int i = 0; i < cubeids.length; i++) {
    		cube = (Cube)super.getService().getIObjectByPK(Cube.class, cubeids[i]);
			String name = new StringBuffer().append(cube.getName()).append("_复制").toString();
			List<Cube> cubes = super.getService().findAllByCriteria(DetachedCriteria.forClass(Cube.class)
					.add(Restrictions.eq("name", name))
					.add(Restrictions.eq("typeid", dicid)));
			if(cubes !=null && cubes.size()>0){
				response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=E_DM_80010001").toString()) ;
				ModelAndView view = request(response,orgi);
				return view ;
			}
		}
    	for (int i = 0; i < cubeids.length; i++) {
			cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeids[i]), true) ;
			cube.setId(null);
			cube.setName(new StringBuffer().append(cube.getName()).append("_复制").toString());
			cube.setTypeid(dicid);
			List<CubeMetadata> metadata = cube.getMetadata();
			List<Dimension> dimension = cube.getDimension();
			List<CubeMeasure> measure = cube.getMeasure();
			super.getService().saveIObject(cube);

			for (int j = 0; j < metadata.size(); j++) {
				metadata.get(j).setId(null);
				metadata.get(j).setCube(cube.getId());
				super.getService().updateIObject(metadata.get(j));
			}

			for (int j = 0; j < dimension.size(); j++) {
				List<CubeLevel> levels = dimension.get(j).getCubeLevel();
				dimension.get(j).setId(null);
				dimension.get(j).setCubeid(cube.getId());
				super.getService().saveIObject(dimension.get(j));
				for (int k = 0; k < levels.size(); k++) {
					levels.get(k).setId(null);
					levels.get(k).setDimid(dimension.get(j).getId());
					levels.get(k).setCubeid(cube.getId());
					super.getService().updateIObject(levels.get(k));
				}
			}

			for (int j = 0; j < measure.size(); j++) {
				measure.get(j).setId(null);
				measure.get(j).setCubeid(cube.getId());
				super.getService().updateIObject(measure.get(j));
			}
		}
    	ModelAndView view = request(response,orgi);
    	return view ;
    }
    /**
     * 模型移动页面加载
     * @param request
     * @param orgi
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubemove" , name="cubemove" , type="dm",subtype="cube")
    public ModelAndView cubemove(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubemove") , orgi) ;
    	view.addObject("cubePackageList", super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("ctype", RivuDataContext.TypeCategory.CUBE.toString())))) ;
    	return view ;
    }
    /**
     * 模型批量移动
     * @param request
     * @param orgi
     * @param cubeids
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubemoveList" , name="cubemoveList" , type="dm",subtype="cube")
    public ModelAndView cubemoveList(HttpServletRequest request , @PathVariable String orgi,@Valid String[] cubeids,@Valid String dicid) throws Exception{  
    	ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=S_DM_80010021").toString()) ;
    	Cube cube = null;
    	for (int i = 0; i < cubeids.length; i++) {
    		cube = (Cube)super.getService().getIObjectByPK(Cube.class, cubeids[i]);
    		List<Cube> cubes = super.getService().findAllByCriteria(DetachedCriteria.forClass(Cube.class)
    				.add(Restrictions.eq("name", cube.getName()))
    				.add(Restrictions.eq("typeid", dicid)));
    		if(cubes !=null && cubes.size()>0){
    			response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=E_DM_80010002").toString()) ;
    			ModelAndView view = request(response,orgi);
    			return view ;
    		}
    	}
    	for (int i = 0; i < cubeids.length; i++) {
			cube = (Cube)super.getService().getIObjectByPK(Cube.class, cubeids[i]);
			cube.setTypeid(dicid);
			super.getService().updateIObject(cube);
		}
    	ModelAndView view = request(response,orgi);
    	return view ;
    }
    /**
     * 模型批量删除
     * @param request
     * @param orgi
     * @param cubeids
     * @param dicid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{dicid}/cubedellist" , name="cubedellist" , type="dm",subtype="cube")
    public ModelAndView cubedellist(HttpServletRequest request , @PathVariable String orgi,@Valid String[] cubeids, @PathVariable String dicid) throws Exception{  
    	ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=S_DM_80010022").toString()) ;
    	int count = 0;
    	boolean flag = true;
    	for (int i = 0; i < cubeids.length; i++) {
    		count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeLevel.class).add(Restrictions.eq("cubeid", cubeids[i])).add(Restrictions.eq("orgi", orgi))) ;
        	if(count>0){
        		flag = false;
        		break;
        	}
        	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeids[i])).add(Restrictions.eq("orgi", orgi))) ;
        	if(count>0){
        		flag = false;
        		break;
        	}
        	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeMetadata.class).add(Restrictions.eq("cube", cubeids[i])).add(Restrictions.eq("orgi", orgi))) ;
        	if(count>0){
        		flag = false;
        		break;
        	}
        	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Dimension.class).add(Restrictions.eq("cubeid", cubeids[i])).add(Restrictions.eq("orgi", orgi))) ;
        	if(count>0){
        		flag = false;
        		break;
        	}
        
		}
    	if(flag){
    		Cube cube = null;
    		for (int i = 0; i < cubeids.length; i++) {
    			cube = new Cube();
    			cube.setId(cubeids[i]);
    			super.getService().deleteIObject(cube);
    		}
    	}else{
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedic/").append(dicid).append(".html?msgcode=E_DM_80010021").toString());
    	}
    	//	super.getService().deleteIObject(super.getService().getIObjectByPK(Cube.class, cubeid));
    	return super.request( response , orgi) ;
    }
    /**
     * 模型详情页面加载
     * @param request
     * @param orgi
     * @param cubeid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/cubedesign/{cubeid}" , name="cubeview" , type="dm",subtype="cube")
    public ModelAndView cubeview(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createDMTempletResponse("/pages/datamodel/cube/cubedesign") , orgi) ;
    	Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
    	view.addObject("cube", cube) ;
    	view.addObject("dim", cube.getDimension().size()>0?cube.getDimension().get(0):null) ;
    	view.addObject("dimlist",super.getService().findAllByCriteria(DetachedCriteria.forClass(Dimension.class).add(Restrictions.eq("cubeid", cubeid)).addOrder(Order.asc("name"))));
    	//view.addObject("measurelist", cube.getMeasure()) ;
    	view.addObject("locationdics",this.getAllParents(cube.getTypeid(), new ArrayList<TypeCategory>(), orgi));
    	view.addObject("measurelist",super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeid)).addOrder(Order.asc("name"))));
    	view.addObject("authlist",authInterface.getReportAuthList(cubeid, orgi)) ;
    	return view;
    }
    
    @RequestMapping(value="/cubeauthlist/{cubeid}" , name="cubeauthlist" , type="dm",subtype="cube")
    public ModelAndView cubeauthlist(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubeauth") , orgi) ;
    	Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
    	view.addObject("cube", cube) ;
    	view.addObject("authlist",authInterface.getReportAuthList(cubeid, orgi)) ;
    	return view;
    }
    
    
    /**
     * 维度编辑页面加载
     * @param request
     * @param orgi
     * @param cubeid
     * @param dimid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/measureauth/{meaid}" , name="measureauth" , type="dm",subtype="cube")
    public ModelAndView measureauth(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@PathVariable String meaid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubeauth") , orgi) ;
		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
		view.addObject("cube",cube);
		view.addObject("measure",super.getService().getIObjectByPK(CubeMeasure.class, meaid));
		view.addObject("authlist",authInterface.getReportAuthList(meaid, orgi)) ;
    	return view;
    }
    
    
    /**
     * 维度编辑页面加载
     * @param request
     * @param orgi
     * @param cubeid
     * @param dimid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/levelauth/{levelid}" , name="levelauth" , type="dm",subtype="cube")
    public ModelAndView levelauth(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@PathVariable String levelid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubeauth") , orgi) ;
		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
		view.addObject("cube",cube);
		view.addObject("cubelevel",super.getService().getIObjectByPK(CubeLevel.class, levelid));
		view.addObject("authlist",authInterface.getReportAuthList(levelid, orgi)) ;
    	return view;
    }
    /**
     * 维度成员列表页
     * @param request
     * @param orgi
     * @param dimid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{dimid}/levellist" , name="levellist" , type="dm",subtype="cube")
    public ModelAndView levellist(HttpServletRequest request , @PathVariable String orgi, @PathVariable String dimid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/levellist") , orgi) ;
    	view.addObject("dim", super.getService().getIObjectByPK(Dimension.class, dimid)) ;
    	return view;
    }
    /**
     * 维度成员编辑页面加载
     * @param request
     * @param orgi
     * @param levelid
     * @param cubeid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{cubeid}/leveledit/{levelid}" , name="leveledit" , type="dm",subtype="cube")
    public ModelAndView leveledit(HttpServletRequest request , @PathVariable String orgi, @PathVariable String levelid, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/leveledit") , orgi) ;
    	view.addObject("level", super.getService().getIObjectByPK(CubeLevel.class, levelid)) ;
    	//view.addObject("level",super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeLevel.class).add(Restrictions.eq("id", levelid)).addOrder(Order.asc("name")))) ;
    	view.addObject("cubeid",cubeid);
    	return view;
    }
    /**
     * 维度成员编辑
     * @param request
     * @param orgi
     * @param level
     * @param cubeid
     * @param dimid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{cubeid}/{dimid}/leveledito" , name="leveledito" , type="dm",subtype="cube")
    public ModelAndView leveledito(HttpServletRequest request , @PathVariable String orgi, @Valid CubeLevel level, @PathVariable String cubeid, @PathVariable String dimid) throws Exception{
    	ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/{dimid}/levellist.html?msgcode=S_DM_80010124").toString()) ;
    	
    	CubeLevel cl = (CubeLevel)super.getService().getIObjectByPK(CubeLevel.class, level.getId());
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeLevel.class).add(Restrictions.eq("dimid", dimid)).add(Restrictions.and(Restrictions.eq("cubeid", cubeid) , Restrictions.eq("name", level.getName())))) ;
    	if(!cl.getName().equals(level.getName())&&count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/{dimid}/levellist.html?msgcode=E_DM_80010125").toString());
    	}else{
    		cl.setName(level.getName());
        	cl.setCode(level.getCode());
        	cl.setType(level.getType());
        	cl.setLeveltype(level.getLeveltype());
        	cl.setPermissions(level.isPermissions());
        	cl.setUniquemembers(level.isUniquemembers());
        	cl.setFormatstr(level.getFormatstr());
        	cl.setSortindex(level.getSortindex());
        	cl.setParameters(level.getParameters());
        	cl.setAttribue(level.getAttribue());
        	cl.setDescription(level.getDescription());
        	super.getService().updateIObject(cl);
    	}
    	ModelAndView view = request(response , orgi) ;
    	return view;
    }
    /**
     * 维度成员删除
     * @param request
     * @param orgi
     * @param levelid
     * @param dimid
     * @return
     */
    @RequestMapping(value = "/{dimid}/leveldel/{levelid}")
    public ModelAndView levelrm(HttpServletRequest request ,@PathVariable String orgi ,@PathVariable String levelid,@PathVariable String dimid) {
		CubeLevel level = (CubeLevel) super.getService().getIObjectByPK(CubeLevel.class, levelid) ;
		super.getService().deleteIObject(level) ; 
		ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/levellist") , orgi) ;
    	view.addObject("dim", super.getService().getIObjectByPK(Dimension.class, dimid)) ;
    	view.addObject("result_msg",LocalTools.getMessage("E_DM_80010117"));
    	return view;
    }
    /**
     * 模型元数据导入页面加载
     * @param request
     * @param orgi
     * @param cubeid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{cubeid}/dbsourceimport" , name="dbsourceimport" , type="dm",subtype="cube")
    public ModelAndView dbsourceimport(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/dbsourceimport") , orgi) ;
    	Cube cube = (Cube)super.getService().getIObjectByPK(Cube.class, cubeid);
    	view.addObject("tablelist", super.getService().findAllByCriteria(DetachedCriteria.forClass(TableTask.class).add(Restrictions.eq("dbid", cube.getDb())).add(Restrictions.eq("orgi", orgi)))) ;//.add(Restrictions.not(Restrictions.eq("tabledirid", "1"))),允许对结算数据查看创建模型了
    	view.addObject("cubeid", cubeid) ;
    	return view;
    }
    
    
    @RequestMapping(value="/{cubeid}/searchtable" , name="searchtable" , type="dm",subtype="cube")
    public ModelAndView searchtable(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid,@Valid String searchkey) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/searchtable") , orgi) ;
    	Cube cube = (Cube)super.getService().getIObjectByPK(Cube.class, cubeid);
    	view.addObject("tablelist", super.getService().findAllByCriteria(DetachedCriteria.forClass(TableTask.class).add(Restrictions.like("name", searchkey, MatchMode.ANYWHERE)).add(Restrictions.eq("dbid", cube.getDb())).add(Restrictions.not(Restrictions.eq("tabledirid", "1"))).add(Restrictions.eq("orgi", orgi)))) ;
    	view.addObject("cubeid", cubeid) ;
    	return view;
    }
    /**
     * 元数据编辑
     * @param request
     * @param orgi
     * @param metaid
     * @param cubeid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/cubemetaedit/{metaid}" , name="cubemetaedit" , type="dm",subtype="cube")
    public ModelAndView cubemetaedit(HttpServletRequest request , @PathVariable String orgi, @PathVariable String metaid,@PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubemetaedit") , orgi) ;
    	CubeMetadata meta = (CubeMetadata)super.getService().getIObjectByPK(CubeMetadata.class, metaid);
    	view.addObject("meta", meta);
    	view.addObject("cubeid", cubeid);
    	return view;
    }
    
//    @RequestMapping(value="{cubeid}/tablefield/{dimid}/{value}" , name="tablefield" , type="dm",subtype="cube")
//    public ModelAndView tablefield(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@PathVariable String dimid,@PathVariable String value) throws Exception{
//    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/tplist") , orgi) ;
//		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
//		if(dimid.equals("0")){
//			view.addObject("name",value);
//		}else{
//			Dimension dim = (Dimension) super.getService().getIObjectByPK(Dimension.class, dimid);
//			dim.setFktable(value);
//			view.addObject("dim",dim);
//		}
//		view.addObject("cube",cube);
//    	return view;
//    }
    
    @RequestMapping(value="/tablefield/{tpid}" , name="tablefield" , type="dm",subtype="cube")
    public ModelAndView tablefield(HttpServletRequest request , @PathVariable String orgi,@PathVariable String tpid) throws Exception{
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/tplist") , orgi) ;
    	view.addObject("tplist",super.getService().findAllByCriteria(DetachedCriteria.forClass(TableProperties.class).add(Restrictions.eq("dbtableid", tpid)).add(Restrictions.eq("orgi", orgi))));
    	return view;
    }
    /**
     * 加载维度添加页面
     * @param request
     * @param orgi
     * @param cubeid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/dimensionadd" , name="dimensionadd" , type="dm",subtype="cube")
    public ModelAndView dimensionadd(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/dimensionadd") , orgi) ;
		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
		view.addObject("cube",cube);
    	return view;
    }
    /**
     * 维度添加
     * @param request
     * @param orgi
     * @param cubeid
     * @param dim
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/dimensionaddo" , name="dimensionaddo" , type="dm",subtype="cube")
    public ModelAndView dimensionaddo(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@Valid Dimension dim) throws Exception{
    	ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=S_DM_80010111").toString()) ;
    	
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Dimension.class).add(Restrictions.eq("name", dim.getName())).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    	if(count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=E_DM_80010112").toString());
    	}else{
    		dim.setCode(RivuTools.getCode());
        	dim.setCreatetime(new Date());
        	super.getService().saveIObject(dim);
    	}
    	ModelAndView view = request(response , orgi) ;
    	return view;
    }
    /**
     * 维度编辑页面加载
     * @param request
     * @param orgi
     * @param cubeid
     * @param dimid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/dimensionedit/{dimid}" , name="dimensionedit" , type="dm",subtype="cube")
    public ModelAndView dimensionedit(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@PathVariable String dimid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/dimensionedit") , orgi) ;
		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
		view.addObject("cube",cube);
		view.addObject("dim",super.getService().getIObjectByPK(Dimension.class, dimid));
    	return view;
    }
    
    
    /**
     * 维度编辑
     * @param request
     * @param orgi
     * @param cubeid
     * @param dim
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/dimensionedito" , name="dimensionedito" , type="dm",subtype="cube")
    public ModelAndView dimensionedito(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@Valid Dimension dim) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/dimlist") , orgi) ;
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Dimension.class).add(Restrictions.eq("name", dim.getName())).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    	Dimension d = (Dimension)super.getService().getIObjectByPK(Dimension.class, dim.getId());
    	if(!d.getName().equals(dim.getName())&&count>0){
    		view.addObject("errormsg", LocalTools.getMessage("E_DM_80010115"));
    		
    	}else{
    		d.setName(dim.getName());
    		d.setPostop(dim.getPostop());
    		d.setType(dim.getType());
    		d.setParameters(dim.getParameters());
    		d.setFkfield(dim.getFkfield());
    		d.setFktable(dim.getFktable());
    		d.setFktableid(dim.getFktableid());
    		d.setAllmembername(dim.getAllmembername());
    		d.setAttribue(dim.getAttribue());

    		super.getService().updateIObject(d);
    	}
    	Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
    	
    	view.addObject("cube", cube) ;
    	return view;
    }
    
    
    
    /**
     * 维度删除
     * @param request
     * @param orgi
     * @param cubeid
     * @param dimid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="{cubeid}/dimensiondelo/{dimid}" , name="dimensiondelo" , type="dm",subtype="cube")
    public ModelAndView dimensiondelo(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@PathVariable String dimid) throws Exception{  
    	ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=S_DM_80010116").toString()) ;
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeLevel.class).add(Restrictions.eq("dimid", dimid)).add(Restrictions.eq("orgi", orgi))) ;
    	if(count>0){
    		response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=E_DM_80010116").toString());
    	}else{
    		Dimension d = new Dimension();
    		d.setId(dimid);
    		super.getService().deleteIObject(d);
    	}
		ModelAndView view = request(response , orgi) ;
    	return view;
    }
    /**
     * 元数据编辑
     * @param request
     * @param orgi
     * @param cubeid
     * @param meta
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{cubeid}/cubemetaedito" , name="cubemetaedito" , type="dm",subtype="cube")
    public ModelAndView cubemetaedito(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid, @Valid CubeMetadata meta) throws Exception{  
    	ModelAndView view = request(new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=S_DM_80010110").toString()) , orgi) ;
    	CubeMetadata m = (CubeMetadata)super.getService().getIObjectByPK(CubeMetadata.class, meta.getId());
    	m.setMtype(meta.getMtype());
    	m.setAttribue(meta.getAttribue());
    	m.setNamealias(meta.getNamealias());
    	super.getService().updateIObject(m);
    	return view;
    }
    /**
     * 元数据删除
     */
    @RequestMapping(value="/{metaid}/cubemetadel" , name="cubemetadel" , type="dm",subtype="cube")
    public ModelAndView cubemetadel(HttpServletRequest request , @PathVariable String orgi, @PathVariable String metaid) throws Exception{  
    	CubeMetadata meta = new CubeMetadata() ;
		meta.setId(metaid);
		CubeMetadata metadata = (CubeMetadata) super.getService().getIObjectByPK(CubeMetadata.class, metaid);
		ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(metadata.getCube()).append(".html?msgcode=S_DM_80010102").toString()) ;
		if(metadata !=null){
			List<Dimension> dimensions = super.getService().findAllByCriteria(DetachedCriteria.forClass(Dimension.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("fktable", metadata.getTb().getName())).add(Restrictions.eq("cubeid", metadata.getCube())));
			List<CubeLevel> cubeLevels = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeLevel.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("tablename", metadata.getTb().getName())).add(Restrictions.eq("cubeid", metadata.getCube())));
			List<CubeMeasure> cubeMeasures = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("tablename", metadata.getTb().getName())).add(Restrictions.eq("cubeid", metadata.getCube())));
			if((dimensions != null && dimensions.size() >0) || (cubeLevels!=null && cubeLevels.size()>0) || (cubeMeasures != null && cubeMeasures.size()>0)){
				responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(metadata.getCube()).append(".html?msgcode=E_DM_80010102").toString()) ;
			}else{
				super.getService().deleteIObject(meta) ;
			}
		}
		ModelAndView view = request(responseData, orgi) ;
    	return view;
//		return request(new ResponseData("/pages/public/success"), orgi) ;
    }
    
    /**
     *元数据导入
     * @param request
     * @param orgi
     * @param cubeid
     * @param tableids
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/dbsourceimporto" , name="dbsourceimporto" , type="dm",subtype="cube")
    public ModelAndView dbsourceimporto(HttpServletRequest request , @PathVariable String orgi, @Valid String cubeid,@Valid String[] tableids) throws Exception{  
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=S_DM_80010101").toString()) ;
    	boolean flag = true;
    	int count = 0;
    	for (int i = 0; i < tableids.length; i++) {
    		count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeMetadata.class).add(Restrictions.eq("tb.id", tableids[i])).add(Restrictions.eq("cube", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    		if(count>0){
    			flag = false;
    			break;
    		}
		}
    	if(flag){
    		CubeMetadata cubeMetaData = null;
        	for(String tableid : tableids){
    			cubeMetaData = new CubeMetadata();
    			cubeMetaData.setCube(cubeid) ;
    			cubeMetaData.setOrgi(orgi) ;
    			cubeMetaData.setTb(new TableTask());
    			cubeMetaData.getTb().setId(tableid) ;
    			super.getService().saveIObject(cubeMetaData) ;
    		}
    	}else{
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=E_DM_80010101").toString());
    	}
    	
    	ModelAndView view = request(responseData, orgi) ;
    	return view;
    }
    /**
     * 维度成员添加
     * @param request
     * @param orgi
     * @param name
     * @param tpid
     * @param cubeid
     * @param dimid
     * @param table
     * @return
     */
    @RequestMapping(value = "/leveladd/{dimid}/{tpid}/{cubeid}/{table}/{name}/{oldname}", name="leveladd" , type="dm",subtype="cube")
    public ModelAndView leveladd(HttpServletRequest request ,@PathVariable String orgi,@PathVariable String name,@PathVariable String oldname,@PathVariable String tpid, @PathVariable String cubeid,@PathVariable String dimid,@PathVariable String table) {
		Dimension dim = (Dimension) super.getService().getIObjectByPK(Dimension.class, dimid) ;
		CubeLevel data = new CubeLevel();
		data.setOrgi(orgi) ;
		data.setCubeid(cubeid) ;
		data.setDimid(dimid) ;
		TableProperties tp = new TableProperties();
		tp.setId(tpid) ;
		data.setTableproperty(tp) ;
		data.setTablename(table) ;
		if(!StringUtils.isBlank(oldname)){
			data.setName(oldname) ;
		}else{
			data.setName(name) ;
		}
		
		data.setCode(name) ;
		data.setColumname(name) ;
		data.setSortindex(dim.getCubeLevel().size()+1) ;
		ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/levellist") , orgi) ;
    	
		List<CubeLevel> measureList = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeLevel.class).add(Restrictions.eq("dimid", dimid)).add(Restrictions.and(Restrictions.eq("cubeid", cubeid) , Restrictions.eq("name", data.getName())))) ;
		if(measureList.size()>0){
			view.addObject("result_msg",LocalTools.getMessage("E_DM_80010120"));
		}else{
			super.getService().saveIObject(data) ;
			view.addObject("result_msg",LocalTools.getMessage("S_DM_80010121"));
		}
		view.addObject("dim", super.getService().getIObjectByPK(Dimension.class, dimid)) ;
    	return view;
    }
    
    
    
    /**
     * 模型指标添加
     * @param request
     * @param orgi
     * @param name
     * @param cubeid
     * @param table
     * @return
     */
	@RequestMapping(value = "/measureadd/{cubeid}/{table}/{name}/{oldname}", name="measureadd" , type="dm",subtype="cube")
    public ModelAndView measureadd(HttpServletRequest request ,@PathVariable String orgi,@PathVariable String name, @PathVariable String cubeid,@PathVariable String table,@PathVariable String oldname) {
		CubeMeasure data = new CubeMeasure();
		data.setOrgi(orgi) ;
		data.setCubeid(cubeid) ;
		data.setTablename(table) ;
		data.setName(name) ;
		data.setCode(name) ;
		data.setColumname(name) ;
		if(!StringUtils.isBlank(oldname)){
			data.setName(oldname) ;
		}else{
			data.setName(name) ;
		}
		List<CubeMeasure> measureList = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.and(Restrictions.eq("cubeid", cubeid) , Restrictions.eq("name", data.getName())))) ;
		ModelAndView view = request(new ResponseData("/pages/datamodel/cube/measurelist") , orgi) ;
		if(measureList.size()>0){
			view.addObject("result_msg",LocalTools.getMessage("E_DM_80010119"));
		}else{
			super.getService().saveIObject(data) ;
			view.addObject("result_msg",LocalTools.getMessage("S_DM_80010119"));
		}
		view.addObject("measurelist", super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi",orgi)))) ;
		return view;
    }
	/**
	 * 模型指标列表
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/measurelist" , name="measurelist" , type="dm",subtype="cube")
    public ModelAndView measurelist(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/measurelist") , orgi) ;
    	view.addObject("measurelist", super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi",orgi)))) ;
    	return view;
    }
	/**
	 * 指标编辑页面加载
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @param measureid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/measureedit/{measureid}" , name="measureedit" , type="dm",subtype="cube")
    public ModelAndView measureedit(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid,@PathVariable String measureid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/measureedit") , orgi) ;
    	view.addObject("measure",super.getService().getIObjectByPK(CubeMeasure.class, measureid));
    	view.addObject("cubeid",cubeid);
    	return view;
    }
	/**
	 * 指标删除
	 * @param request
	 * @param orgi
	 * @param mid
	 * @param cubeid
	 * @return
	 */
	@RequestMapping(value = "/{cubeid}/measuredelo/{mid}" ,name="measuredelo" , type="dm",subtype="cube")
    public ModelAndView measuredelo(HttpServletRequest request ,@PathVariable String orgi ,@PathVariable String mid,@PathVariable String cubeid) {
		CubeMeasure measure = (CubeMeasure) super.getService().getIObjectByPK(CubeMeasure.class, mid) ;
		List<CubeMeasure> measureList = super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.and(Restrictions.eq("orgi", orgi) , Restrictions.eq("measure.id", measure.getId())))) ;
		ModelAndView view = request(new ResponseData("/pages/datamodel/cube/measurelist") , orgi) ;
    	
		if(measureList!=null && measureList.size()>0){
			Cube cube = (Cube) super.getService().getIObjectByPK(Cube.class, measureList.get(0).getCubeid()) ;
			view.addObject("result_msg",LocalTools.getMessage("E_DM_80010118")+cube.getName());
		}else{
			view.addObject("result_msg",LocalTools.getMessage("S_DM_80010118"));
			super.getService().deleteIObject(measure) ;
		}
		view.addObject("measurelist", super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi",orgi)))) ;
		return view ;
    }
	/**
	 * 指标编辑
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @param cm
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="{cubeid}/measureedito" , name="measureedito" , type="dm",subtype="cube")
    public ModelAndView measureedito(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid,@Valid CubeMeasure cm) throws Exception{  
		ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/{cubeid}/measurelist.html?msgcode=S_DM_80010126").toString()) ;
		int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("name", cm.getName())).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
    	CubeMeasure c = (CubeMeasure)super.getService().getIObjectByPK(CubeMeasure.class, cm.getId());
    	if(!c.getName().equals(cm.getName())&&count>0){
    		response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/{cubeid}/measurelist.html?msgcode=E_DM_80010125").toString()) ;
    	}else{
    		c.setName(cm.getName());
    		c.setCode(cm.getCode());
    		c.setAggregator(cm.getAggregator());
    		c.setFormatstring(cm.getFormatstring());
    		c.setCalculatedmember(cm.isCalculatedmember());
    		c.setSortindex(cm.getSortindex());
    		c.setParameters(cm.getParameters());
    		c.setAttribue(cm.getAttribue());
    		c.setDescription(cm.getDescription());
    		super.getService().updateIObject(c);
    	}
    	return request(response , orgi);
    	
    }
	
	
	
	/**
	 * 模型维度成员清空
	 * @param request
	 * @param orgi
	 * @param dimid
	 * @return
	 */
	@RequestMapping(value = "{dimid}/levelclear",name="levelclear" , type="dm",subtype="cube")
    public ModelAndView levelclear(HttpServletRequest request ,@PathVariable String orgi,@PathVariable String dimid) {
		ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/levellist") , orgi) ;
		Dimension dim = (Dimension) super.getService().getIObjectByPK(Dimension.class, dimid) ;
		if(dim!=null && dim.getCubeLevel().size()>0){
			Iterator iterator = dim.getCubeLevel().iterator() ;
			while(iterator.hasNext()){
				super.getService().deleteIObject(iterator.next()) ;
			}
		}
		view.addObject("result_msg",LocalTools.getMessage("S_DM_80010122"));
		
		view.addObject("dim", super.getService().getIObjectByPK(Dimension.class, dimid)) ;
		return view;
    }
	/**
	 * 模型指标清空
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/{cubeid}/measureclear", name="measureclear" , type="dm",subtype="cube")
    public ModelAndView measureclear(HttpServletRequest request ,@PathVariable String orgi,@PathVariable String cubeid) throws Exception {
		List<CubeMeasure> measurelist =  super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi",orgi)));
		ModelAndView view = request(new ResponseData("/pages/datamodel/cube/measurelist") , orgi) ;
		boolean flag = true;
		int count = 0;
		for (int i = 0; i < measurelist.size(); i++) {
			count = super.getService().getCountByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.and(Restrictions.eq("orgi", orgi) , Restrictions.eq("measure.id", measurelist.get(i).getId())))) ;
			if(count>0){
				flag=false;
				break;
			}
		}
		if(flag){
			for (int i = 0; i < measurelist.size(); i++) {
				super.getService().deleteIObject(measurelist.get(i));
			}
			
			view.addObject("result_msg",LocalTools.getMessage("S_DM_80010123"));
		}else{
			view.addObject("result_msg",LocalTools.getMessage("E_DM_80010123"));
		}
		view.addObject("measurelist", measurelist =  super.getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.eq("cubeid", cubeid)).add(Restrictions.eq("orgi",orgi)))) ;
		return view ;
    }
	/**
	 * 模型保存成json
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="{cubeid}/cubevalid" , name="cubevalid" , type="dm",subtype="cube")
    public ModelAndView cubevalid(HttpServletRequest request , @PathVariable String orgi,@PathVariable String cubeid) throws Exception{
		ResponseData response = new ResponseData("/pages/datamodel/cube/cubevalid") ;
		ModelAndView view = request(response , orgi) ;
		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
		boolean hasMasterTable  = false ;
		boolean incremental = false ;
		for(CubeMetadata meta : cube.getMetadata()){
			if("0".equals(meta.getMtype())){//设置为主表
				hasMasterTable = true ;
				if(meta.getTb()!=null && meta.getTb().getPreviewtemplet()!=null && meta.getTb().getPreviewtemplet().length()>0){
					DefaultParam defaultParam = JSON.parseObject(meta.getTb().getPreviewtemplet(), DefaultParam.class) ;
					for(DefaultValue value : defaultParam.getValues()){
						if(StringUtils.isBlank(value.getValue())){
							incremental = true ;
							break ;
						}
					}
				}
			}
		}
		if(!hasMasterTable){
			view.addObject("ation_message", LocalTools.getMessage("E_DM_80010131")) ;
		}else if(incremental){
			view.addObject("ation_message", LocalTools.getMessage("E_DM_80010132")) ;
		}else if(RivuDataContext.CubeEnum.CUBE.toString().equals(cube.getDstype())&&cube.getMeasure().size()==0){
			view.addObject("ation_message", LocalTools.getMessage("E_DM_80010134")) ;
		}else{
			/**
			 * 验证是否有语法错误
			 */
			DataSource dataSource = ServiceHelper.getDataModelService(cube) ;
			try{
				dataSource.valid(cube) ;
				view.addObject("ation_message", LocalTools.getMessage("S_DM_80010100")) ;
				view.addObject("success", "success") ;
			}catch(Exception ex){
				ex.printStackTrace();
				view.addObject("ation_message", LocalTools.getMessage("E_DM_80010133")+ex.getMessage()) ;
			}
		}
//		super.getService().updateIObject(cube);
    	return view ;
    }
	/**
	 * 模型导出cub文件
	 * @param request
	 * @param response
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "{cubeid}/cubedownload",name="cubedownload" , type="dm",subtype="cube")
    public ModelAndView  cubedownload(HttpServletRequest request ,HttpServletResponse response , @PathVariable String orgi,@PathVariable String cubeid) throws IOException {
		response.setContentType("text/html;charset=UTF-8");
		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
		response.setContentType("charset=UTF-8;application/octet-stream");   
		response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(cube.getName(), "UTF-8" )+".cub");   
		OutputStream out = response.getOutputStream() ;
		try{
			out.write(RivuTools.encryption(JSON.toJSONString(cube)).getBytes());
			out.flush();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	/**
	 * 模型发布页面加载
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/cubepublish" , name="cubepublish" , type="dm",subtype="cube")
    public ModelAndView cubepublish(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/cubepublish") , orgi) ;
    	
    	ModelAndView tempView = this.cubevalid(request, orgi, cubeid) ;
    	view.addObject("cubeid",cubeid);
    	return tempView!=null && tempView.getModelMap().get("success")==null ? tempView : view;
    }
	
	/**
	 * 模型发布页面加载
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/authroles" , name="cubeauth" , type="dm",subtype="cube")
    public ModelAndView cubeauth(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/authroles") , orgi) ;
    	view.addObject("cube",super.getService().getIObjectByPK(Cube.class, cubeid));
    	view.addObject("type","cube");
    	view.addObject("roles",UserAuthzFactory.getInstance(orgi).getRoles(orgi));
    	//根据资源id获取权限，用于回显
    	view.addObject("auths",UserAuthzFactory.getInstance(orgi).getAuth(cubeid,orgi));
    	return view;
    }
	
	/**
	 * 模型授权访问
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/authrolesdo" , name="authrolesdo" , type="dm",subtype="cube")
    public ModelAndView authrolesdo(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid,@Valid String[] userid) throws Exception{  
		ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html").toString()) ;
		ModelAndView view = request(response , orgi);
		if(userid!=null&&userid.length>0){
			List<Auth> autoList = new ArrayList<Auth>();
			String resourceid="";
			String resourcetype = "";
			if(request.getParameter("measureid")!=null){
				resourcetype = Auth.RESOURCE_TYPE_MEASURE ;
				resourceid = request.getParameter("measureid").toString() ;
				view = this.measureauth(request, orgi, cubeid, resourceid) ;
			}else if(request.getParameter("levelid")!=null){
				resourcetype = Auth.RESOURCE_TYPE_LEVEL ;
				resourceid = request.getParameter("levelid").toString() ;
				view = this.levelauth(request, orgi, cubeid, resourceid) ;
			}else{
				resourcetype = Auth.RESOURCE_TYPE_MODEL ;
				resourceid = cubeid;
				view = this.cubeauthlist(request, orgi, cubeid) ;
			}
			for (String string : userid) {//user_
				if(string.indexOf("_")>0){
					String ownertype = string.substring(0 , string.indexOf("_"));
					if(string.length()>(string.indexOf("_")+1)){
						String ownerid = string.substring(string.indexOf("_")+1);
						String authtype = request.getParameter(ownerid);
						
						Auth auth = new Auth() ;
						auth.setAuthread(authtype) ;//用来控制禁止或允许访问
		//				auth.setResourcedic(cubeid) ;
						auth.setDataid(cubeid);
						auth.setResourceid(resourceid);
						auth.setResourcetype(resourcetype);
						
						auth.setResourcedic(Auth.RESOURCE_DIC_N) ;
						auth.setOwnerid(ownerid) ;
						if(ownertype.equals("organ")){
							auth.setOwnertype(Auth.OWNER_TYPE_ORGAN) ;
						}else if(ownertype.equals("role")){
							auth.setOwnertype(Auth.OWNER_TYPE_ROLE) ;
						}else{//剩下的都是user
							auth.setOwnertype(Auth.OWNER_TYPE_USER) ;
						}
						
						auth.setOrgi(orgi) ;
						auth.setCreatetime(new Date()) ;
						autoList.add(auth) ;
						super.getService().execByHQL("delete from Auth where resourceid='"+resourceid+"' and ownerid='"+ownerid+"'") ;
					}
				}
			}

			
			
			super.getService().saveBat(autoList) ;
			if(request.getParameter("measureid")!=null){
				view = this.measureauth(request, orgi, cubeid, resourceid) ;
			}else if(request.getParameter("levelid")!=null){
				view = this.levelauth(request, orgi, cubeid, resourceid) ;
			}else{
				view = this.cubeauthlist(request, orgi, cubeid) ;
			}
		}
		
    	return view;
    }
	
	
	
	/**
	 * 模型授权访问
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/roleauthdel/{authid}" , name="authrolesdo" , type="dm",subtype="cube")
    public ModelAndView authrolesdo(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid, @PathVariable String authid) throws Exception{  
		ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html").toString()) ;
		Auth auth = new Auth();
		auth.setId(authid) ;
		super.getService().deleteIObject(auth) ;
		ModelAndView view = request(response , orgi);
		if(request.getParameter("measureid")!=null){
			view = this.measureauth(request, orgi, cubeid, request.getParameter("measureid")) ;
		}else if(request.getParameter("levelid")!=null){
			view = this.levelauth(request, orgi, cubeid, request.getParameter("levelid")) ;
		}else{
			view = this.cubeauthlist(request, orgi, cubeid) ;
		}
		
    	return view;
    }
	
	/**
	 * 模型发布页面加载
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/authrolesadd" , name="authrolesadd" , type="dm",subtype="cube")
    public ModelAndView authrolesadd(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/authroles") , orgi) ;
    	view.addObject("cube",super.getService().getIObjectByPK(Cube.class, cubeid));
    	view.addObject("type","cube");
    	view.addObject("roles",UserAuthzFactory.getInstance(orgi).getRoles(orgi));
    	return view;
    }
	
	/**
	 * 模型发布页面加载
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/authroles/{measureid}" , name="measureauthroles" , type="dm",subtype="cube")
    public ModelAndView measureauthroles(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid, @PathVariable String measureid) throws Exception{  
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/authroles") , orgi) ;
    	view.addObject("cube",super.getService().getIObjectByPK(Cube.class, cubeid));
    	view.addObject("measure",super.getService().getIObjectByPK(CubeMeasure.class, measureid));
    	view.addObject("type","measure");
    	view.addObject("roles",UserAuthzFactory.getInstance(orgi).getRoles(orgi));
    	view.addObject("auths",UserAuthzFactory.getInstance(orgi).getAuth(measureid,orgi));
    	return view;
    }
	/**
	 * 远程数据源加载
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/remotedbsourcelist" , name="remotedbsourcelist" , type="dm",subtype="cube")
    public ModelAndView remotedbsourcelist(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
		String url = request.getParameter("url");
    	ModelAndView view = request(super.createPageResponse("/pages/datamodel/cube/remotedbsourcelist") , orgi) ;
    	String jsonO = null;
		try {
			jsonO = RivuTools.getURL(new StringBuffer().append(url).append("/api/cube/getDBSourceListJSON.html").toString());
			view.addObject("sourcelist",JSON.parseObject(jsonO , List.class));
		} catch (Exception e) {
			e.printStackTrace();
			view.addObject("result_msg",LocalTools.getMessage("E_DM_80010128"));
		}
    	return view;
    }
	/**
	 * 模型远程发布
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @param isRecover
	 * @param url
	 * @param dbsourceid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/remotepublish" , name="remotepublish" , type="dm",subtype="cube")
    public ModelAndView remotepublish(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid, @Valid String isRecover,@Valid String url,@Valid String dbsourceid,@Valid String freshetl) throws Exception{
		ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=S_DM_80010129").toString()) ;
		
		Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
		cube.setAuthList(RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Auth.class).add(Restrictions.eq("dataid",cube.getId()))));
		PublishedCube publishCube = new  PublishedCube();
		BeanUtils.copyProperties(publishCube, cube) ;
		publishCube.setDbid(cube.getDb());
		publishCube.setDb(RivuDataContext.TabType.PUB.toString());
		publishCube.setCubecontent(JSON.toJSONString(cube)) ;
		publishCube.setDataid(cube.getId());
		publishCube.setDiclocation(getParent(cube.getTypeid() , orgi));
		User user = (User)super.getService().getIObjectByPK(User.class, super.getUser(request).getId());
		publishCube.setUserid(user.getId());
    	publishCube.setUsername(user.getUsername());
		List<NameValuePair> nvps=new ArrayList<NameValuePair>();  
		nvps.add(new BasicNameValuePair("isRecover", isRecover)) ;
		nvps.add(new BasicNameValuePair("freshetl", freshetl)) ;
		nvps.add(new BasicNameValuePair("dbsourceid", dbsourceid)) ;
		nvps.add(new BasicNameValuePair("publishcubejson", RivuTools.encryption(JSON.toJSONString(publishCube)))) ;
		
		String result = RivuTools.postData(new StringBuffer().append(url).append("/api/cube/cubepublish.html").toString(), nvps);
		if("dbSource_exist".equals(result)){//数据库已存在，导入失败
			response.setPage(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=E_DM_80010129").toString());
		}
		ModelAndView view = request(response, orgi) ;
    	return view;
    }
	/**
	 * 模型本地发布
	 * @param request
	 * @param orgi
	 * @param cubeid
	 * @param isRecover
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/{cubeid}/{isRecover}/{freshetl}/localpublish" , name="localpublish" , type="dm",subtype="cube")
    public ModelAndView localpublish(HttpServletRequest request , @PathVariable String orgi, @PathVariable String cubeid, @PathVariable String isRecover,@PathVariable boolean freshetl) throws Exception{
		ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/dm/cube/cubedesign/").append(cubeid).append(".html?msgcode=S_DM_80010128").toString()) ;
    	ModelAndView view = request(response , orgi) ;
    	User user = super.getUser(request);
    	Cube cube = super.loadCubeData(orgi, (Cube) super.getService().getIObjectByPK(Cube.class, cubeid), true) ;
    	cube.setAuthList(RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Auth.class).add(Restrictions.eq("dataid",cube.getId()))));
    	PublishedCube publishCube  = new PublishedCube();
    	BeanUtils.copyProperties(publishCube, cube) ;
    	publishCube.setId(null);
    	publishCube.setDbid(cube.getDb());
    	publishCube.setDb(RivuDataContext.TabType.PUB.toString());
    	List<PublishedCube> pbCubeList = super.getService().findPageByCriteria(DetachedCriteria.forClass(PublishedCube.class).add(Restrictions.eq("dataid", cubeid)).add(Restrictions.eq("orgi", orgi)).addOrder(Order.desc("dataversion")) , 1 , 1) ;
    	publishCube.setCubecontent(JSON.toJSONString(cube)) ;
    	publishCube.setDataid(cubeid);
    	publishCube.setDiclocation(getParent(cube.getTypeid() , orgi));
    	publishCube.setUserid(user.getId());
    	publishCube.setUsername(user.getUsername());
    	publishCube.setCreatetime(new Date());
    	if(pbCubeList.size()>0){
    		int maxVersion = pbCubeList.get(0).getDataversion() ;
    		if("yes".equals(isRecover)){
    			publishCube.setId(pbCubeList.get(0).getId()) ;
    			super.getService().updateIObject(publishCube) ;
        	}else if("no".equals(isRecover)){
        		publishCube.setDataversion(maxVersion+1) ;
        		publishCube.setCreatetime(new Date());
        		
        		super.getService().saveIObject(publishCube) ;
        	}else{
        		List<PublishedCube> cubeList = super.getService().findAllByCriteria(DetachedCriteria.forClass(PublishedCube.class).add(Restrictions.eq("dataid", cubeid)).add(Restrictions.eq("orgi", orgi))) ;
        		for (int i = 0; i < cubeList.size(); i++) {
					super.getService().deleteIObject(cubeList.get(i));
				}
        		publishCube.setDataversion(1) ;
        		super.getService().saveIObject(publishCube) ;
        	}
    	}else{
    		publishCube.setDataversion(1) ;
    		super.getService().saveIObject(publishCube) ;
    	}
    	if(freshetl){
    		List<JobDetail> joblist = super.getService().findAllByCriteria(DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("taskid", publishCube.getId())).add(Restrictions.eq("orgi", orgi))) ;
    		if(joblist.size()>0){
    			List<TableTask> tableTaskList = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(TableTask.class).add(Restrictions.and(Restrictions.eq("orgi", orgi) , Restrictions.eq("id", joblist.get(0).getCrawltask())))) ;
    			if(tableTaskList.size()>0){
    				TableTask task = tableTaskList.get(0) ;
    				task.setUserpage(true);
    				task.setDatasql(DatabaseMetaDataHandler.getCubeSQL(cube , orgi , task));
    				super.getService().updateIObject(task);
    			}
    		}
    	}
    	
    	return view;
    }
	/**
	 * 查询模型目录路径
	 * @param id当前模型目录
	 * @param str
	 * @param orgi
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private String getParent(String id,String orgi){
		StringBuffer strb = new StringBuffer() ;
		List<TypeCategory> cat = super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("ctype",RivuDataContext.TypeCategoryEnum.CUBE.toString())).add(Restrictions.eq("orgi",orgi)));
		TypeCategory parent = null ;
		while(parent==null || parent.getParentid()==null || parent.getParentid().equals("0")){
			parent = null ;
			for(TypeCategory type : cat){
				if(type.getId().equals(id)){
					parent = type ;
					id = parent.getParentid();
					break ;
				}
			}
			if(parent!=null){
				strb.insert(0, parent.getName()).insert(0,"/");
			}else{
				break ;
			}
		}
		return strb.toString();
	}
	
	@SuppressWarnings("unchecked")
	private List<TypeCategory> getAllParents(String id,List<TypeCategory> dics,String orgi){
		if("0".equals(id))return dics;
		
		List<TypeCategory> diclist = super.getService().findAllByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("orgi",orgi)));
		TypeCategory parent = null ;
		while(parent==null){
			for(TypeCategory type : diclist){
				if(type.getId().equals(id)){
					parent = type ;
					id = parent.getParentid();
					break ;
				}
			}
			if(parent!=null){
				dics.add(parent);
				parent = null;
			}else{
				break ;
			}
		}
		return dics;
	}
	
    
} 